package com.rajesh.messageservice;

import android.app.ActivityManager;
import android.app.IntentService;
import android.content.Intent;
import android.content.Context;

import com.rajesh.messageservice.helper.ServiceHelper;

public class ProtectorService extends IntentService {
    private static final String ACTION_CHECK_PROTECTOR_RUNNING = "rajesh.action.CHECK_PROTECTOR_RUNNING";
    public static final String ServiceProtectorAction = "com.rajesh.action.START_PROTECTOR";
    public static final String ProtectorPackageName = "com.rajesh.messageserviceprotector";
    public ProtectorService() {
        super("MsgIntentSvc");
    }

    public static void startActionCheckProtectorRunning(Context context) {
        Intent intent = new Intent(context, ProtectorService.class);
        intent.setAction(ACTION_CHECK_PROTECTOR_RUNNING);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_CHECK_PROTECTOR_RUNNING.equals(action)) {
                handleActionCheckProtectorRunning();
            }
        }
    }

    private void handleActionCheckProtectorRunning() {
        try{
            boolean isServiceRunning = false;
            ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                if(ProtectorPackageName.equals(service.service.getPackageName()))
                    isServiceRunning = true;
            }
            if (!isServiceRunning) {
                Intent msgSvcIntent = new Intent(ServiceProtectorAction);
                msgSvcIntent = ServiceHelper.transferImplicitIntent(this, msgSvcIntent);

                if(msgSvcIntent != null){
                    startService(msgSvcIntent);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
